package com.haizhi.crm.biz.service.impl;

import com.haizhi.crm.biz.constant.*;
import com.haizhi.crm.biz.dao.UserShareDao;
import com.haizhi.crm.biz.model.*;
import com.haizhi.crm.biz.service.UserShareService;
import com.haizhi.crm.biz.task.message.engine.MessageActualPush;
import com.haizhi.crm.biz.task.message.model.ContextDto;
import com.haizhi.crm.common.constant.BizStatus;
import com.haizhi.crm.common.exception.UnexpectedStatusException;
import com.haizhi.crm.common.model.Response;
import com.haizhi.crm.common.util.CommonUtils;
import com.haizhi.crm.sys.auth.dao.DepartmentDao;
import com.haizhi.crm.sys.auth.dao.InstitutionDao;
import com.haizhi.crm.sys.auth.dao.UserDao;
import com.haizhi.crm.sys.auth.model.DepartmentVo;
import com.haizhi.crm.sys.auth.model.InstitutionDo;
import com.haizhi.crm.sys.auth.model.ShareTargetUserVo;
import com.haizhi.crm.sys.auth.model.UserVo;
import com.haizhi.crm.sys.message.dao.MessageCategoryDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * Created by yangyijun on 2018/5/17.
 */
@Service
public class UserShareServiceImpl implements UserShareService {
    @Autowired
    private UserShareDao userShareDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private MessageCategoryDao messageCategoryDao;

    @Autowired
    private MessageActualPush messageActualPush;
    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private InstitutionDao institutionDao;


    @Override
    public Response share(UserShareQo userShareQo) {
        try {
            Long fromUserId = CommonUtils.getUserID();
            Long[] toUserIds = userShareQo.getToUserIds();
            List<UserShareDo> userShareDos = new LinkedList<>();
            for (Long toUserId : toUserIds) {
                UserShareDo userShareDo = new UserShareDo();
                userShareDo.setUpdatedDt(new Date());
                userShareDo.setCreatedDt(new Date());
                userShareDo.setBatchNo(userShareQo.getBatchNo());
                userShareDo.setEnabledFlag("1" );
                userShareDo.setEntityKey(userShareQo.getEntityKey());
                userShareDo.setEntityType(userShareQo.getEntityType());
                userShareDo.setFromUserId(fromUserId);
                userShareDo.setToUserId(toUserId);
                userShareDo.setShareMsg(userShareQo.getShareMsg());
                userShareDo.setCreatedById(fromUserId);
                userShareDo.setUpdateById(fromUserId);
                userShareDos.add(userShareDo);
            }
            List<UserShareDo> userShareDos1 = userShareDao.save(userShareDos);
            pushMessage(userShareDos1);
            return Response.success();
        } catch (Exception e) {
            throw new UnexpectedStatusException(BizStatus.USER_SHARE_ERROR, e);
        }
    }

    @Override
    public Response findShareTargets(String name) {
        try {
            List<ShareTargetTreeVo> shareTargetTreeVos = new ArrayList<>();
            List<InstitutionDo> institutionDos = institutionDao.findAll();
            for (InstitutionDo institutionDo : institutionDos) {
                //1.设置机构
                ShareTargetTreeVo institution = new ShareTargetTreeVo();
                institution.setId("insti_" + institutionDo.getId());
                institution.setName(institutionDo.getName());

                //2.设置部门
                List<ShareTargetTreeVo> detpTrees = getTargetDeptTreeVos(institutionDo, name);
                institution.setChildren(detpTrees);
                shareTargetTreeVos.add(institution);
            }
            return Response.success(shareTargetTreeVos);
        } catch (Exception e) {
            throw new UnexpectedStatusException(BizStatus.FIND_SHARE_TARGET_ERROR, e);
        }
    }

    private List<ShareTargetTreeVo> getTargetDeptTreeVos(InstitutionDo institutionDo, String name) {
        List<DepartmentVo> deptVos = departmentDao.findByInstitutionId(institutionDo.getId());
        if (CollectionUtils.isEmpty(deptVos)) {
            return null;
        }
        List<DepartmentVo> deptVoTrees = DepartmentVo.buildTree(deptVos);
        List<ShareTargetTreeVo> detpTrees = new ArrayList<>();
        for (DepartmentVo dept : deptVoTrees) {
            ShareTargetTreeVo targetDept = new ShareTargetTreeVo();
            targetDept.setId("dept_" + dept.getId());
            targetDept.setName(dept.getName());

            List<ShareTargetUserVo> shareTargetUserVos = null;
            if (StringUtils.isBlank(name)) {
                shareTargetUserVos = userDao.findByDepartmentId(dept.getId());
            } else {
                shareTargetUserVos = userDao.findBy(dept.getId(), name);
            }
            if (CollectionUtils.isEmpty(shareTargetUserVos)) {
                continue;
            } else {
                for (ShareTargetUserVo shareTargetUserVo : shareTargetUserVos) {
                    ShareTargetTreeVo targetUser = new ShareTargetTreeVo();
                    targetUser.setId(shareTargetUserVo.getId().toString());
                    targetUser.setName(shareTargetUserVo.getName());
                    targetDept.addChildren(targetUser);
                }
            }
            detpTrees.add(targetDept);
        }
        return detpTrees;
    }

    public void pushMessage(List<UserShareDo> userShareDos) {
        ContextDto contextDto = new ContextDto();
        UserShareDo userShareDoOne = userShareDos.get(0);
        contextDto.setMsgType(ShareType.getMsgTypeByShare(userShareDoOne.getEntityType()));
        contextDto.setMsgSchema(MessageType.SHARE);
        contextDto.setEventType(userShareDoOne.getEntityType());
        contextDto.setDetailKey(userShareDoOne.getId() + "" );
        contextDto.setDatabases(MysqlConstant.DATABASE);
        String userName = "";
        UserVo userVo = userDao.findBy(userShareDoOne.getFromUserId());
        if (userVo != null) {
            userName = userVo.getName();
        }
        contextDto.setTitle(userName + "向你分享了" + userShareDoOne.getShareMsg());
        contextDto.setMsgCategoryId(messageCategoryDao.findByName(contextDto.getMsgType()).get(0).getId());
        Map<Long, MessageUserVo> messageUserVoMap = new HashMap<>();
        for (UserShareDo userShareDo : userShareDos) {
            MessageUserVo messageUserVo = new MessageUserVo();
            messageUserVo.setUserId(userShareDo.getToUserId());
            messageUserVo.setStatus(MessageStatus.UNREAD);
            List<MessageUserResourceDo> messageUserResourceDos = new ArrayList<>();
            MessageUserResourceDo messageUserResourceDo = new MessageUserResourceDo();
            messageUserResourceDo.setMessageSourceType(MessageSourceType.SHARE);
            messageUserResourceDos.add(messageUserResourceDo);
            messageUserVo.setMessageUserResourceDoList(messageUserResourceDos);
            messageUserVoMap.put(userShareDo.getToUserId(), messageUserVo);
        }
        contextDto.setMessageUserVoMap(messageUserVoMap);
        messageActualPush.push(contextDto);


    }
}
